package se.kth.andreost;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;
import android.widget.Toast;

public class ServerCommunicator {
	
	private static final String HOST = "130.237.226.21";
	private static final int PORT = 1231;
	
	private Socket socket;
	private BufferedReader socketIn;
	private PrintWriter socketOut;
	


	public ServerCommunicator(){
		try {
			ServerCommunicator.this.socket = new Socket(HOST, PORT);
			ServerCommunicator.this.socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			ServerCommunicator.this.socketOut = new PrintWriter(socket.getOutputStream(), true);
			Log.d(ChatClientApp.LOGTAG, "Ansluten till servern!");
			connect("AndroidOfDoom");
		} catch (UnknownHostException e) {
			Log.d(ChatClientApp.LOGTAG, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(ChatClientApp.LOGTAG, "Kunde inte ansluta: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void connect(String name) {
		socketOut.println("CONNECT / " + name);
	}
	
	public boolean isErrorMsg(String msg){
		Pattern p = Pattern.compile("^ERROR / connection$");
		Matcher m = p.matcher(msg);
		return m.matches();
	}
	public String readLine() throws IOException{
			return socketIn.readLine();
	}
	
	public boolean write(String chatMsg){
		socketOut.println("WRITE / " + chatMsg);
		if (socketOut.checkError())
			return false;
		else 
			return true;
	}
}
